//////////////////////////////////////////////////////////////////////////
///	\file:	SocketManager.h
///	Copyright (MingYou) 2009 - All Rights Reserved
///	Author:	Robert.Ma
///	Date:	[2009/05/19]
///	Description:
///		
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "MThread.h"
#include "ISocketManager.h"



class CSocketReader;
class CSocketWriter;

class CSocketManager : public ISocketManager, public CMThread
{
public:
	//////////////////////////////////////////////////////////////////////////
	CSocketManager(void);
	virtual ~CSocketManager(void);

	virtual BOOL IsConnected();
	virtual BOOL Connect(const BYTE* pszAddr, int iPort);

	virtual int Write(const BYTE* pData, DWORD dwLen);

	virtual BOOL Initialize(INetCallback* pCallback);
	virtual BOOL IsCacheFull();

	virtual void CloseNet();
	virtual BOOL OpenNet();

protected:
	virtual DWORD Execute();

	virtual void PreCreate();
	virtual void AfterCreate();
	virtual void PreClose();
	virtual void AfterClose();

private:
	enum socketState {NONE = 0, DISCONNECTING, CREATED, CONNECTED, ACCEPTING};

	static BOOL OpenWSA();
	static void CloseWSA();

	void OnConnected();
	void OnSend();
	void OnRecv();
	void OnClose(int iErrorID);

	BOOL SocketCreate();
	BOOL SocketSetAddress();
	BOOL SocketConnect();
	void SocketDisConnect();

	BOOL DoConnect();
	void DoDisConnect();

	void Release();

	BOOL SetAddress(LPCSTR pszAddr, int iPort);

	void DelayCheckConnection(DWORD dwDelay);

	void StartReadThread();
	void StartWriteThread();
	void EndReadThread();
	void EndWriteThread();


	static BOOL		m_bWSAStarted;

	SOCKADDR_IN		m_remoteAddress;
	SOCKET			m_Socket;

	char			m_szAddr[UCHAR_MAX];
	int				m_iRemotePort;
	int				m_iErrorCode;
	socketState		m_socketState;

	INetCallback*	m_pCallback;
	CSocketReader*	m_pNetRead;
	CSocketWriter*	m_pNetWrite;
};
